const app = getApp();

Page({
  data: {
    book: {
      id:'',
      title: '',
      author: '',
      publisher: '',
      publicationYear: '',
      isbn: '',
      bookCondition: '',
      price: '',
      description: '',
      imageUrl: '',
      category: '',
      sellerId: '',
    },
    url: '',
    bookId: null,
  },
  onPullDownRefresh(){
    this.onLoad()
},
  onLoad(options) {
    const { id } = options; // 获取图书ID
    this.setData({
      bookId: id,
      'book.id':id,
      url: app.imgUrl,
    });
    this.getBookDetails(id); // 调用获取图书详情方法
    wx.stopPullDownRefresh()
  },

  getBookDetails(id) {
    const token = wx.getStorageSync('token');
    wx.request({
      url: `${app.apiUrl}/books/${id}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        token: token,
      },
      success: res => {
        if (res.data.code === 1) {
          this.setData({
            book: res.data.data,
          });
        } else {
          wx.showToast({ title: '获取图书信息失败', icon: 'error' });
        }
      },
      fail: () => {
        wx.showToast({ title: '请求失败', icon: 'error' });
      },
    });
  },

  handleInputChange(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({
      [`book.${field}`]: e.detail,
    });
  },

  updateBook() {
    const token = wx.getStorageSync('token');
    const book = this.data.book;
    wx.request({
      url: `${app.apiUrl}/books/update`, // 调用更新接口
      method: 'PUT',
      header: {
        'Content-Type': 'application/json',
        token: token,
      },
      data: book,
      success: res => {
        if (res.data.code === 1) {
          wx.showToast({ title: '修改成功', icon: 'success' });
          wx.navigateBack();
        } else {
          wx.showToast({ title: '修改失败', icon: 'error' });
        }
      },
      fail: () => {
        wx.showToast({ title: '请求失败', icon: 'error' });
      },
    });
  },

  uploadImage() {
    wx.chooseImage({
      count: 1,
      sourceType: ['album', 'camera'],
      success: res => {
        const imageUrl = res.tempFilePaths[0];
        
        wx.uploadFile({
          url: `${app.apiUrl}/common/upload`,
          filePath: imageUrl,
          name: 'file',
          success: uploadRes => {
            const data = JSON.parse(uploadRes.data);
            this.setData({
              'book.imageUrl': data,
            });
            wx.showToast({ title: '上传成功', icon: 'success' });
          },
          fail: () => {
            wx.showToast({ title: '上传失败', icon: 'error' });
          }
        });
      }
    });
  }
});
